<template>
  <div class="app-container">
    <div class="top-bar-container">
      <el-alert
        :title="title"
        type="info"
        :closable="false"
      />
    </div>

    <el-tree
      ref="tree"
      :data="treeData"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="treeDefaultCheckedKeys"
      :props="treeProps"
    />

    <div class="buttons">
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </div>

  </div>
</template>

<script>
import { adminRoleCheckablePermissionList, adminRoleAssignPermission } from '@/api/rest/admin'

export default {
  name: 'RoleAssignPermission',
  data() {
    return {
      title: '',
      roleId: null,
      role: null,
      treeData: null,
      treeDefaultCheckedKeys: null,
      treeProps: {
        children: 'subList',
        label: 'name'
      }
    }
  },
  watch: {
    $route(to, from) {
      this.roleId = this.$route.query.roleId || 0
      this.getPermissionTree()
    }
  },
  created() {
    this.roleId = this.$route.query.roleId || 0
    this.getPermissionTree()
  },
  methods: {
    getPermissionTree() {
      adminRoleCheckablePermissionList(this.roleId).then(response => {
        this.role = response.data.role
        this.title = `为角色 ${this.role.name} 分配权限`
        this.treeData = response.data.checkableList
        this.treeDefaultCheckedKeys = response.data.checkedIdList
      })
    },
    handleSubmit() {
      const checkedPermissionIds = this.$refs.tree.getCheckedKeys()
      const halfCheckedPermissionIds = this.$refs.tree.getHalfCheckedKeys()
      adminRoleAssignPermission({ roleId: this.roleId, checkedPermissionIds, halfCheckedPermissionIds }).then(response => {
        this.$message({
          message: '分配角色权限成功',
          type: 'success'
        })
        this.getPermissionTree()
      })
    }
  }
}
</script>
<style scoped>
.buttons {
  margin-top: 10px;
}
</style>

